<template>
  <div class="map-picker">
    <div ref="mapContainer" class="map-container"></div>
    <div class="selected-location">
      已选坐标：{{
        selectedLocation
          ? `${selectedLocation.lng}, ${selectedLocation.lat}`
          : '未选择'
      }}
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import AMapLoader from '@amap/amap-jsapi-loader'

const props = defineProps(['modelValue'])
const emit = defineEmits(['update:modelValue'])

const mapContainer = ref(null)
const map = ref(null)
const selectedLocation = ref(null)

// 初始化地图
onMounted(async () => {
  await AMapLoader.load({
    key: 'your-amap-key', // 替换为实际高德API Key
    version: '2.0',
    plugins: ['AMap.Geocoder']
  })

  map.value = new AMap.Map(mapContainer.value, {
    zoom: 12,
    center: [116.397428, 39.90923]
  })

  map.value.on('click', handleMapClick)
})

// 地图点击处理
const handleMapClick = (e) => {
  selectedLocation.value = {
    lng: e.lnglat.getLng(),
    lat: e.lnglat.getLat()
  }
  emit('update:modelValue', selectedLocation.value)
}

// 外部值同步
watch(
  () => props.modelValue,
  (newVal) => {
    if (newVal) {
      map.value.setCenter([newVal.lng, newVal.lat])
    }
  }
)
</script>

<style scoped>
.map-picker {
  border: 1px solid #ddd;
  border-radius: 4px;
  overflow: hidden;
}

.map-container {
  width: 100%;
  height: 300px;
}

.selected-location {
  padding: 10px;
  background: #f8f9fa;
  border-top: 1px solid #eee;
  font-size: 0.9em;
}
</style>
